import json


class Teacher:
    def __init__(self, name, age):
        self.name = name
        self.age = age


# 自定义JSON编码器
def teacher_info_encoder(obj):
    if isinstance(obj, Teacher):
        return obj.__dict__  # 返回对象属性字典
    raise TypeError(f"{obj} is not JSON serializable")


# json.dumps - 用于将一个python对象序列化为json编码字符串
def json_dumps():
    data = {
        "name": "张三",
        "age": 18,
        "hobbies": ["reading", "music"],
        "info": {
            "address": "北京市朝阳区",
            "phone": "18888888888"
        }
    }
    json_str = json.dumps(data, ensure_ascii=False, indent=4)
    print(json_str)


def object_hook(obj):
    print("obj")


# json.loads - 用于将一个json编码的字符串解码为python对象
def json_loads():
    json_str = '''
    {
        "name": "李四",
        "age": 25,
        "hobbies": ["swimming", "playing games"],
        "info": {
            "address": "上海市黄浦区",
            "phone": "16666666666"
        }
    }
    '''
    data = json.loads(json_str, object_hook=object_hook)
    print(type(data))
    print(data)


# json.load 从文件中读取json数据
# json.dump 将json数据写入到文件中
def json_load_and_json_dump():
    # 1.从test.json中读取内容
    with open('test.json', 'r') as readFile:
        data = json.load(readFile)
    with open('test.json', 'w') as writeFile:
        json.dump(Teacher("Alice", 20), writeFile, default=teacher_info_encoder, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    # 创建一个StudentInfo对象
    teacher = Teacher("Alice", 20)
    # 将对象转换为JSON字符串，指定自定义的编码器
    json_string = json.dumps(teacher, default=teacher_info_encoder)
    print(json_string)

    json_dumps()
    json_loads()
    json_load_and_json_dump()
